package com.zxp.web.sys_role.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxp.web.VO.ResultUtils;
import com.zxp.web.VO.ResultVO;
import com.zxp.web.sys_role.entity.RolePram;
import com.zxp.web.sys_role.entity.SelectItem;
import com.zxp.web.sys_role.entity.SysRole;
import com.zxp.web.sys_role.service.SysRoleService;
import com.zxp.web.sys_role_menu.entity.SaveMenuParam;
import com.zxp.web.sys_role_menu.service.SysRoleMenuService;
import com.zxp.web.sys_user_role.entity.SysUserRole;
import com.zxp.web.sys_user_role.service.SysUserRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author MasterZ
 * @Date 2025/9/30 16:52
 */
@RequestMapping("/api/role")
@RestController
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 新增角色
     *
     * @param sysRole 角色
     * @return 新增结果
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:role:add')")
    public ResultVO add(@RequestBody SysRole sysRole) {
        if (sysRoleService.save(sysRole)) {
            return ResultUtils.success("新增成功！");
        }
        return ResultUtils.error("新增失败！");
    }

    /**
     * 根据id删除角色
     *
     * @param roleId 角色ID
     * @return 删除结果
     */
    @DeleteMapping("/{roleId}")
    public ResultVO delete(@PathVariable("roleId") Long roleId) {
        if (sysRoleService.removeById(roleId)) {
            return ResultUtils.success("删除成功！");
        }
        return ResultUtils.error("删除失败！");
    }

    /**
     * 查询角色列表
     *
     * @param param 查询条件
     * @return 结果
     */
    @GetMapping("/getList")
    public ResultVO getList(RolePram param) {
        IPage<SysRole> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(param.getRoleName())) {
            queryWrapper.lambda().like(SysRole::getRoleName, param.getRoleName());
        }
        //按创建时间倒序
        queryWrapper.lambda().orderByDesc(SysRole::getCreateTime);
        IPage<SysRole> sysRoleIPage = sysRoleService.page(page, queryWrapper);
        return ResultUtils.success("查询成功", sysRoleIPage);
    }

    /**
     * 编辑更新角色信息
     *
     * @param sysRole 角色参数
     * @return 更新结果
     */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:role:edit')")
    public ResultVO edit(@RequestBody SysRole sysRole) {
        if (sysRoleService.updateById(sysRole)) {
            return ResultUtils.success("更新成功！");
        }
        return ResultUtils.error("更新失败！");
    }

    /*
    角色下拉数据
     */
    @GetMapping("/selectList")
    public ResultVO selectList() {
        List<SysRole> sysRoleList = sysRoleService.list();
        List<SelectItem> selectItems = new ArrayList<>();
        Optional.ofNullable(sysRoleList).orElse(new ArrayList<>()).forEach(item -> {
            SelectItem vo = new SelectItem();
            vo.setChecked(false);
            vo.setLabel(item.getRoleName());
            vo.setValue(item.getRoleId());
            selectItems.add(vo);
        });
        return ResultUtils.success("查询成功", selectItems);
    }

    //角色是否被占用，删除前先查询是否占用
    @GetMapping("/isUsed")
    public ResultVO isUsed(Long roleId) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getRoleId, roleId);
        long count = sysUserRoleService.count(queryWrapper);
        return ResultUtils.success("查询成功", count != 0);
    }

    //保存角色菜单
    @PostMapping("/saveRoleMenu")
    public ResultVO saveRoleMenu(@RequestBody SaveMenuParam param) {
        sysRoleMenuService.saveRoleMenu(param);
        return ResultUtils.success();
    }
}
